package com.heima.Serivce.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.exception.RabbitMQcode;
import com.heima.model.common.Pojos.WAMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.FailureCallback;
import org.springframework.util.concurrent.SuccessCallback;

@Service
@Slf4j
public class WemediaMQ implements com.heima.Serivce.WemediaMQ {
    @Autowired
    RabbitTemplate rabbitTemplate;

//    发布消息
    public void pushmassge(Long id,Boolean IsDown)
    {
//        配置ConfirmCallBack
        CorrelationData correlationData=SetCallback(id);
        WAMessage waMessage=new WAMessage();
        waMessage.setArticleId(id);
        waMessage.setIsDown(IsDown);
//        发送消息
//        这里转成json是因为只能传字符串
        String jsonString = JSON.toJSONString(waMessage);
        rabbitTemplate.convertAndSend(RabbitMQcode.ArticleExchangeName,"",jsonString,correlationData);
    }

//    发送消息给ESscearch微服务
    public void pushmassgeToES(Long id)
    {
//        配置ConfirmCallBack
        CorrelationData correlationData=SetCallback(id);

        String idString =id.toString();
        rabbitTemplate.convertAndSend(RabbitMQcode.ESExchangeName,"",idString,correlationData);
    }

    private CorrelationData SetCallback(Long id)
    {
        //        配置ConfirmCallBack
        CorrelationData correlationData=new CorrelationData(id.toString());
        correlationData.getFuture().addCallback(new SuccessCallback<CorrelationData.Confirm>() {
            @Override
            public void onSuccess(CorrelationData.Confirm confirm) {
                if(confirm.isAck())
                    log.info("消息发送成功，id:{}",correlationData.getId());

                else
                    log.error("消息发送到交换机失败，id:{},原因:{}",correlationData.getId(),confirm.getReason());
            }
        }, new FailureCallback() {
            @Override
            public void onFailure(Throwable throwable) {
                log.error("消息发送失败，id:{},愿因:{}",correlationData.getId(),throwable.getMessage());
            }
        });
        return correlationData;
    }
}
